package com.cloud.util.QrCord

import com.qiniu.common.QiniuException
import com.qiniu.storage.BucketManager
import com.qiniu.storage.UploadManager
import com.qiniu.util.Auth
import com.qiniu.util.Base64
import com.qiniu.util.StringMap
import com.qiniu.util.UrlSafeBase64
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import java.awt.image.BufferedImage
import java.io.ByteArrayOutputStream
import java.io.IOException
import javax.imageio.ImageIO

class QiniuCloudUtil {

    val upToken: String
        get() = auth.uploadToken(bucketname, null, 3600, StringMap().put("insertOnly", 1))

    // 普通上传
    @Throws(IOException::class)
    fun upload(filePath: String, fileName: String): String? {
        // 创建上传对象
        val uploadManager = UploadManager()
        try {
            // 调用put方法上传
            val token = auth.uploadToken(bucketname)
            if (token == null || token == "") {
                println("未获取到token，请重试！")
                return null
            }
            val res = uploadManager.put(filePath, fileName, token)
            // 打印返回的信息
            println(res.bodyString())
            if (res.isOK) {
                val ret = res.jsonToObject(Ret::class.java)
                //如果不需要对图片进行样式处理，则使用以下方式即可
                //return DOMAIN + ret.key;
                return DOMAIN + ret.key + "?" + style
            }
        } catch (e: QiniuException) {
            val r = e.response
            // 请求失败时打印的异常的信息
            println(r.toString())
            try {
                // 响应的文本信息
                println(r.bodyString())
            } catch (e1: QiniuException) {
                // ignore
            }

        }

        return null
    }

    fun getBytes(img: BufferedImage): ByteArray? {
        val baos = ByteArrayOutputStream()//io流
        ImageIO.write(
                img,
                "jpeg",
                baos
        )//写入流中
        val bytes = baos.toByteArray()//转换成字节
        /*val encoder = BASE64Encoder()
        var png_base64 = encoder.encodeBuffer(bytes).trim()//转换成base64串
        png_base64 = png_base64.replace("\n".toRegex(), "").replace("\r".toRegex(), "")//删除 \r\n*/
        return bytes
    }


    //base64方式上传
    @Throws(Exception::class)
    fun put64image(base64: ByteArray, key: String): String {
        val file64 = Base64.encodeToString(base64, 0)
        val l = base64.size
        val url = "http://upload.qiniu.com/putb64/" + l + "/key/" + UrlSafeBase64.encodeToString(key)
        //非华东空间需要根据注意事项 1 修改上传域名
        val rb = RequestBody.create(null, file64)
        val request = Request.Builder().url(url).addHeader("Content-Type", "application/octet-stream")
                .addHeader("Authorization", "UpToken $upToken")
                .post(rb).build()
        //System.out.println(request.headers());
        val client = OkHttpClient()
        val response = client.newCall(request).execute()
        println(response)
        //如果不需要添加图片样式，使用以下方式
        return DOMAIN + key
        //return DOMAIN + key + "?" + style;
    }


    // 普通删除(暂未使用以下方法，未测试)
    @Throws(IOException::class)
    fun delete(key: String) {
        var key = key
        // 实例化一个BucketManager对象
        val bucketManager = BucketManager(auth)
        // 此处的33是去掉：http://ongsua0j7.bkt.clouddn.com/,剩下的key就是图片在七牛云的名称
        val index= key.lastIndexOf("/")
        key = key.substring(index+1)
        try {
            // 调用delete方法移动文件
            bucketManager.delete(bucketname, key)
        } catch (e: QiniuException) {
            // 捕获异常信息
            val r = e.response
            println(r.toString())
        }

    }

    internal inner class Ret {
        var fsize: Long ?= null
        var key: String? = null
        var hash: String? = null
        var width: Int ?= null
        var height: Int ?= null
    }

    companion object {

        // 设置需要操作的账号的AK和SK
        private val ACCESS_KEY = "cskdMs6nH5es8GoKo7MpgyIXNw1dgwdqxxZhL8nS"
        private val SECRET_KEY = "kFZVDR3yfpwzLT5DHEwUnYeJHoc1hUjGe_vsv8-J"

        // 要上传的空间
        val bucketname = "huangtest"

        // 密钥
        private val auth = Auth.create(ACCESS_KEY, SECRET_KEY)

        val DOMAIN = "http://pnvuywhh6.bkt.clouddn.com/"

        private val style = "自定义的图片样式"
    }


}

